import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class RedisHashDemo {
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.flushAll();
//            test1(jedis);
//            test2(jedis);
//            test3(jedis);
//            test4(jedis);
            test5(jedis);
        }
    }

    private static void test5(Jedis jedis) {
        System.out.println("hmset and hmget");

        Map<String, String> map = new HashMap<>();
        map.put("f1", "1");
        map.put("f2", "2");
        map.put("f3", "3");
        jedis.hmset("k1", map);
        // 这里的 k-v 是一一对应的
        List<String> vals = jedis.hmget("k1", "f1", "f2", "f3", "f4");
        System.out.println("vals: " + vals);
    }

    private static void test4(Jedis jedis) {
        System.out.println("hkeys and hvals");

        jedis.hset("k1", "f1", "111");
        jedis.hset("k1", "f2", "aaa");
        jedis.hset("k1", "f3", "333");

        Set<String> keys = jedis.hkeys("k1");
        List<String> vals = jedis.hvals("k1");
        // 注意： 此时k-v不一定一一对应
        System.out.println("keys: " + keys);
        System.out.println("vals: " + vals);
    }

    private static void test3(Jedis jedis) {
        System.out.println("hdel");

        jedis.hset("k1", "f1", "111");
        jedis.hset("k1", "f2", "111");
        jedis.hset("k1", "f3", "111");
        long result = jedis.hdel("k1", "f1", "f2");
        System.out.println("result: " + result);

        System.out.println("f1: " + jedis.hexists("k1", "f1"));
        System.out.println("f2: " + jedis.hexists("k1", "f2"));
        System.out.println("f3: " + jedis.hexists("k1", "f3"));
    }

    private static void test2(Jedis jedis) {
        System.out.println("hexists");

        jedis.hset("k1", "f1", "111");
        jedis.hset("k1", "f2", "222");
        System.out.println("f1: " + jedis.hget("k1", "f1"));
        System.out.println("f2: " + jedis.hget("k1", "f2"));
        System.out.println("f3: " + jedis.hget("k1", "f3"));
    }

    private static void test1(Jedis jedis) {
        System.out.println("hset and hget");

        Map<String, String> map = new HashMap<>();
        map.put("f1", "1");
        map.put("f2", "2");
        map.put("f3", "3");
        jedis.hset("k1", map);

        System.out.println("result: " + jedis.hget("k1", "f1"));
        System.out.println("result: " + jedis.hget("k1", "f2"));
        System.out.println("result: " + jedis.hget("k1", "f3"));
        System.out.println("result: " + jedis.hget("k1", "f5"));
    }
}
